package cn.com.dhc.danlu.business.shopcar.holder;

import android.graphics.Paint;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import java.math.BigDecimal;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.delivery.order.viewholder.BaseViewHolder;
import cn.com.dhc.danlu.business.shopcar.bean.MerchBean;
import cn.com.dhc.danlu.business.shopcar.callback.IMerchDataChangeCallback;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.home.NumEditext;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.ModifyShoppingCartCountRequest;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.ModifyShoppingCartCountResponse;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.ToShoppingcartResponse.SellerListBean.MerchListBean.PromotionModelListBean;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;
import static cn.com.dhc.danlu.util.CommonConst.ShoppingCarModel.ADD_SHOPPINGCAR_ERROR_3;


/**
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-02-27 17:04
 *
 * <p>
 * 商品视图 ViewHolder
 * </p>
 */
public class MerchViewHolder extends BaseViewHolder<MerchBean> implements View.OnClickListener {
    private ImageView ivSel;
    private SimpleDraweeView sdvGoods;
    private TextView tvName;
    private TextView tvBarcode;
    private TextView tvPromotion;
    private TextView tvUsePromotion;
    private TextView tvPriceUnit;
    private TextView tvPriceAvg;
    private TextView tvPriceAvgTip;
    private TextView tvNoGoods;
    private LinearLayout llPromotion;
    private RelativeLayout rlPriceArea;
    private NumEditext neCount;

    private IMerchDataChangeCallback onMerchClick;

    public MerchViewHolder(View itemView, IMerchDataChangeCallback callback) {
        super(itemView);

        this.onMerchClick = callback;

        initViews();
        setViews();
    }

    private void initViews() {
        ivSel = (ImageView) itemView.findViewById(R.id.iv_sel);
        sdvGoods = (SimpleDraweeView) itemView.findViewById(R.id.sdv_goods);
        tvName = (TextView) itemView.findViewById(R.id.tv_name);
        tvBarcode = (TextView) itemView.findViewById(R.id.tv_barcode);
        tvPromotion = (TextView) itemView.findViewById(R.id.tv_promotion);
        tvUsePromotion = (TextView) itemView.findViewById(R.id.tv_use_promotion);
        tvPriceUnit = (TextView) itemView.findViewById(R.id.tv_price_unit);
        tvPriceAvg = (TextView) itemView.findViewById(R.id.tv_price_avg);
        tvPriceAvgTip = (TextView) itemView.findViewById(R.id.tv_price_avg_tip);
        tvNoGoods = (TextView) itemView.findViewById(R.id.tv_no_goods);
        llPromotion = (LinearLayout) itemView.findViewById(R.id.ll_promotion);
        rlPriceArea = (RelativeLayout) itemView.findViewById(R.id.rl_price_area);
        neCount = (NumEditext) itemView.findViewById(R.id.ne_count);
    }

    private void setViews() {
        // 增加中划线
        tvPriceUnit.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        ivSel.setOnClickListener(this);
        tvUsePromotion.setOnClickListener(this);

        // TODO: 2017/3/9 1. 访问网络，将数据上传服务器 @lyf #ok
        // TODO: 2017/3/9 2. 回调至购物车主界面，重新计算价格 @lyf #ok
        // FIXME: 2017/3/15 修复每次字符变动都会上报服务器的问题 @lyf
        neCount.setDelayTimes(750);
        neCount.setOnOperationListener(new NumEditext.OnOperationListener() {
            @Override
            public void onReduce(View v) {
            }

            @Override
            public void onPlus(View v) {
            }

            @Override
            public void onCountChanged(int count) {
                // 1. 数据上报给服务器
                if (Integer.parseInt(data.getMerchQuantity()) != count) {
                    modifyMerchCount(data, String.valueOf(count));
                }
            }
        });
    }

    /**
     * 修改商品数量
     *
     * @param merch
     *         商品信息
     * @param newCount
     *         新的商品数量
     */
    private void modifyMerchCount(final MerchBean merch, final String newCount) {
        // 建立请求体
        ModifyShoppingCartCountRequest request = new ModifyShoppingCartCountRequest();
        request.setToken(agent.getToken());
        request.setShoppingCartId(merch.getId());
        request.setMerchId(merch.getMerchId());
        request.setMerchCount(newCount);
        request.setSellerId(merch.getSellerId());

        // 添加促销参数
        if (merch.isSelPromotion()) {
            PromotionModelListBean promotionInfo = merch.getPromotionModelList().get(merch.getSelPromotionIndex());
            request.setUsePromotion(CommonConst.PromotionConst.USE_PROMOTION_TYPE_0);
            request.setPromotionId(promotionInfo.getPromotionId());
            request.setPromotionType(promotionInfo.getPromotionType());
            request.setReductionType(promotionInfo.getReductionType());
            request.setRuleId(promotionInfo.getRuleId());
        } else {
            request.setUsePromotion(CommonConst.PromotionConst.USE_PROMOTION_TYPE_1);
            request.setPromotionId(null);
            request.setReductionType(null);
            request.setRuleId(null);
        }

        // 发起网络访问
        agent.getApi()
                .modifyShoppingCartCount(request)
                .compose(OperatorUtils.<ModifyShoppingCartCountResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<ModifyShoppingCartCountResponse>(getContext(), R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(ModifyShoppingCartCountResponse response) {
                        // 如果最小起售数量发生了变化
                        if (CommonConst.ShoppingCarModel.REACH_MINI_STARTSALE_QUANTITY_0.equals(response.getReachMiniStartSaleQuantity())) {
                            // 修改数量小于最小起售量
                            ToastUtil.getInstance().show(R.string.cart_reachMiniStartSaleQuantity_tips);
                            neCount.setDefaultCount(Integer.parseInt(merch.getMerchQuantity()));
                        } else {
                            if (merch.isSelPromotion()) {
                                PromotionModelListBean promotion = merch.getPromotionModelList().get(merch.getSelPromotionIndex());
                                promotion.setIsPromotion(response.getIsPromotion());
                                if (!TextUtils.isEmpty(response.getDiffPrice())) {
                                    promotion.setDiffPrice(response.getDiffPrice());
                                }
                                if (!TextUtils.isEmpty(response.getPromotionType())) {
                                    switch (response.getPromotionType()) {
                                        case CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_1:
                                            // 满减单
                                            promotion.setPromotionType(CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_1);
                                            promotion.setReductionType(CommonConst.PromotionConst.REDUCTION_TYPE_0);
                                            break;
                                        case CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_2:
                                            // 满减总
                                            promotion.setPromotionType(CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_1);
                                            promotion.setReductionType(CommonConst.PromotionConst.REDUCTION_TYPE_1);
                                            break;
                                        default:
                                            // 限购 & 满赠
                                            promotion.setPromotionType(response.getPromotionType());
                                            if (!TextUtils.isEmpty(response.getPresentationInfo())) {
                                                promotion.setPresentationDetail(response.getPresentationInfo());
                                            }
                                            if (!TextUtils.isEmpty(response.getLimitTimesLeft())) {
                                                promotion.getLimitRuleList().get(0).setLimitNumber(response.getLimitTimesLeft());
                                            }
                                            break;
                                    }
                                }
                            }

                            // 2. 在 onSuccess 中设置商品的数量 & 价格
                            merch.setMerchQuantity(newCount);
                            if (!TextUtils.isEmpty(response.getUnitPrice())) {
                                merch.setUnitPrice(response.getUnitPrice());
                            }
                            // 3. 在 onSuccess 中将结果回调给前台
                            onMerchClick.onMerchCountChange(merch.getSellerIndex(), getLayoutPosition() - 1, response.getGiftList());
                        }
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        if (code.equals(ADD_SHOPPINGCAR_ERROR_3)) {
                            return getContext().getString(R.string.modify_shopping_cart_error_3);
                        } else {
                            return getContext().getString(R.string.modify_shopping_cart_error);
                        }
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        neCount.setDefaultCount(Integer.parseInt(merch.getMerchQuantity()));
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    @Override
    protected void bindViewData(MerchBean data) {
        // 设置商品顶的促销信息 - start
        if (null == data.getPromotionModelList() || data.getPromotionModelList().isEmpty()) {
            llPromotion.setVisibility(View.GONE);
        } else {
            llPromotion.setVisibility(View.VISIBLE);
        }
        if (data.getSelPromotionIndex() == data.getPromotionModelList().size()) {
            tvPromotion.setText(R.string.no_selected_promotion);
        } else {
            tvPromotion.setText(data.getPromotionModelList().get(data.getSelPromotionIndex()).getPromotionInfo());
        }
        // 设置商品顶的促销信息 - end

        // TODO: 2017/3/9 在缺货等状态下，选中按钮应该是不可用状态才对 @lyf #ok
        ivSel.setSelected(data.isSelected());
        ivSel.setEnabled(data.isEnable());

        sdvGoods.setImageURI(data.getPicUrl());
        tvName.setText(data.getMerchName());
        tvBarcode.setText("商品条码：".concat(data.getMerchBarCode()));
        if (null != data.getMerchQuantity()) {
            neCount.setDefaultCount(Integer.parseInt(data.getMerchQuantity()));
        } else {
            neCount.setDefaultCount(1);
        }

        switch (data.getMerchStatus()) {
            /*
             * 前四种情况下，需要把选中状态设置为不可用状态，即置灰
             * 第四种情况需要特殊处理，仔细查看一下之前的代码！！
             */
            case CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_1:
                sdvGoods.setAlpha(.5f);
                rlPriceArea.setVisibility(View.GONE);
                tvNoGoods.setVisibility(View.VISIBLE);
                tvNoGoods.setText(R.string.shopping_cart_goods_quehuo);
                break;

            case CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_2:
                sdvGoods.setAlpha(.5f);
                rlPriceArea.setVisibility(View.GONE);
                tvNoGoods.setVisibility(View.VISIBLE);
                tvNoGoods.setText(R.string.shopping_cart_goods_yixiajia);
                break;

            case CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_3:
                sdvGoods.setAlpha(.5f);
                rlPriceArea.setVisibility(View.GONE);
                tvNoGoods.setVisibility(View.VISIBLE);
                tvNoGoods.setText(R.string.shopping_cart_goods_yishixiao);
                break;

            case CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_4:
                sdvGoods.setAlpha(.5f);
                rlPriceArea.setVisibility(View.GONE);
                tvNoGoods.setVisibility(View.VISIBLE);
                tvNoGoods.setText(R.string.shopping_cart_goods_noexist);
                break;

            /*
             * 1. 仔细查看这里的价格对应关系
             */
            case CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_0:
            default:
                // FIXME: 2017/3/9 价格关系的对应需要处理 这里不一定正确 @lyf #ok
                // FIXME: 2017/3/20 购物车单位，统一使用的是 getUnitPrice()，中划线划掉的是计算后的新价格，即均价，conf by why 2017-03-10 11:17:40 #ok
                // FIXME: 2017/3/20 满减单也需要中划线，但是不显"均价"； 限购显示"均价" @lyf
                setPriceAreaView(data);
                break;

        }
    }

    private void setPriceAreaView(MerchBean data) {
        tvNoGoods.setVisibility(View.GONE);
        rlPriceArea.setVisibility(View.VISIBLE);

        if (null == data.getAveragePrice()) {
            tvPriceUnit.setVisibility(View.GONE);
            tvPriceAvgTip.setVisibility(View.GONE);
            tvPriceAvg.setText("￥".concat(CommonUtils.fenToYuan(new BigDecimal(data.getUnitPrice())).toPlainString()).concat("/").concat(data.getSpecName()));
        } else {
            if (data.getReduceType().equals(CommonConst.PromotionConst.REDUCTION_TYPE_0)
                    && data.getSelPromotionType().equals(CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_1)) {
                // 满减单
                tvPriceAvgTip.setVisibility(View.GONE);
                if (data.getAveragePrice().compareTo(new BigDecimal(data.getUnitPrice())) == 0) {
                    tvPriceUnit.setVisibility(View.GONE);
                } else {
                    tvPriceUnit.setVisibility(View.VISIBLE);
                    tvPriceUnit.setText("￥".concat(CommonUtils.fenToYuan(new BigDecimal(data.getUnitPrice())).toPlainString()));
                }
            } else if (data.getSelPromotionType().equals("4")) {
                // 限购
                tvPriceAvgTip.setVisibility(View.VISIBLE);
                tvPriceUnit.setVisibility(View.VISIBLE);
                tvPriceUnit.setText("￥".concat(CommonUtils.fenToYuan(new BigDecimal(data.getUnitPrice())).toPlainString()));
            } else {
                tvPriceUnit.setVisibility(View.GONE);
                tvPriceAvgTip.setVisibility(View.GONE);
            }
            tvPriceAvg.setText("￥".concat(CommonUtils.fenToYuan(data.getAveragePrice()).toPlainString()).concat("/").concat(data.getSpecName()));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_sel:
                data.setSelected(!ivSel.isSelected());
                onMerchClick.onMerchSel(data.getSellerIndex(), getLayoutPosition() - 1);
                break;

            case R.id.tv_use_promotion:
                // TODO: 2017/3/9 弹出选择优惠的选择窗口 @lyf #ok
                // 非编辑状态下 弹出选择优惠
                if (!data.isEditMode()) {
                    onMerchClick.showPromotionsSelect(getLayoutPosition() - 1);
                }
                break;

            default:
                break;
        }
    }
}
